package com.heima.admin.services.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.mapper.AdSensitiveMapper;
import com.heima.admin.services.WemediaNewsAutoScanService;
import com.heima.aliyun.GreenImageScan;
import com.heima.aliyun.GreenTextScan;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.heima.model.wemedia.pojos.WmNews.Status.PUBLISHED;

@Service
@Slf4j
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {
    @Autowired
    WemediaFeign wemediaFeign;
    @Value("${file.oss.web-site}")
    String webSite;
    @Autowired
    GreenTextScan greenTextScan;
    @Autowired
    GreenImageScan greenImageScan;
    @Autowired
    AdChannelMapper adChannelMapper;
    @Autowired
    ArticleFeign articleFeign;
@GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void autoScanByMediaNewsId(Integer wmNewsId) {
        if (wmNewsId == null) {
            log.error("自动审核失败     文章id为空");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        ResponseResult<WmNews> wmNewsResult = wemediaFeign.findById(wmNewsId);
        if (wmNewsResult.getCode().intValue() != 0) {
            log.error("自动审核失败     远程查询文章信息失败，原因：{}", wmNewsResult.getErrorMessage());
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        WmNews wmNews = wmNewsResult.getData();
        if (wmNews == null) {
            log.error("自动审核失败      未查询到自媒体文章信息，wmNewsId：{}", wmNewsId);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Short status = wmNews.getStatus();
        if ((status.shortValue() == WmNews.Status.ADMIN_SUCCESS.getCode() || status.shortValue() == WmNews.Status.SUCCESS.getCode())
                && wmNews.getPublishTime().getTime() <= System.currentTimeMillis()) {
            publishArticle(wmNews);
            return;

        }
        if (status.shortValue() == WmNews.Status.SUBMIT.getCode()) {
            Map<String, Object> contentAndImagesResult = handleTextAndImages(wmNews);
            boolean isSensitive = handleSensitive((String) contentAndImagesResult.get("content"), wmNews);
            if (!isSensitive) return;
            boolean isTextScan = handleTextScan((String) contentAndImagesResult.get("content"), wmNews);
            if (!isTextScan) return;
            Object images = contentAndImagesResult.get("images");
            if (images != null) {
                boolean isImageScan = handImageScan((List<String>) images, wmNews);
                if (!isImageScan) return;
            }
            if (wmNews.getPublishTime().after(new Date())) {
                updateWmNews(wmNews, WmNews.Status.SUCCESS.getCode(), "文章审核通过，待发布");
                return;
            }
            publishArticle(wmNews);

        }
    }

    private boolean handImageScan(List<String> images, WmNews wmNews) {
        boolean flag = true;
        try {

            Map map = greenImageScan.imageUrlScan(images);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "block":
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "图片中有违规内容审核失败，转为人工审核");
                    flag = false;
                    break;
                case "review":
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "图片中有不确定内容，转为人工审核");
                    flag = false;
                    break;

            }
        } catch (Exception e) {
            log.error("文章阿里云图片审核失败，转入人工审核, 原因：{}", e.getMessage());
            e.printStackTrace();
            updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文章阿里云图片审核失败,转入需要人工审核");
            flag = false;
        }

        return flag;
    }


    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = true;
        try {

            Map map = greenTextScan.greenTextScan(content);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "block":
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "文本中有违规内容审核失败，转为人工审核");
                    flag = false;
                    break;
                case "review":
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文本中有不确定内容，转为人工审核");
                    flag = false;
                    break;
            }
        } catch (Exception e) {
            log.error("文章阿里云内容审核失败，转入人工审核, 原因：{}", e.getMessage());
            e.printStackTrace();
            updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文章阿里云内容审核失败,转入需要人工审核");
            flag = false;
        }

        return flag;
    }

    @Autowired
    AdSensitiveMapper adSensitiveMapper;

    //检测内容是否包含敏感词
    private boolean handleSensitive(String content, WmNews wmNews) {
        boolean flag = true;
        List<String> allSensitives = adSensitiveMapper.findAllSensitives();
        SensitiveWordUtil.initMap(allSensitives);
        Map<String, Integer> resultMap = SensitiveWordUtil.matchWords(content);
        if (resultMap != null && resultMap.size() > 0) {
            updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "内容中包含敏感词" + resultMap);
            flag = false;
        }

        return flag;
    }

    private void updateWmNews(WmNews wmNews, short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        ResponseResult responseResult = wemediaFeign.updateWmNews(wmNews);
        if (responseResult.getCode().intValue() != 0) {
            log.error("远程  调用修改自媒体文章出错，原因：{} ,参数{}", responseResult.getErrorMessage(), wmNews);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, responseResult.getErrorMessage());
        }
    }

    //抽取文本中所有内容和图片路径
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        String contentJson = wmNews.getContent();
        if (StringUtils.isBlank(contentJson)) {
            log.error("自动审核失败   文章内容为空");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章内容不存在 ");
        }
        List<Map> contentMaps = JSONArray.parseArray(contentJson, Map.class);
        String content = contentMaps.stream()
                .filter(map -> "text".equals(map.get("type")))
                .map(map -> (String) map.get("value"))
                .collect(Collectors.joining("_hmtt_"));
        content = content + "_hmtt_" + wmNews.getTitle();

        List<String> imageList = contentMaps.stream()
                .filter(map -> "image".equals(map.get("type")))
                .map(map -> (String) map.get("value"))
                .collect(Collectors.toList());
        String imageCover = wmNews.getImages();
        if (StringUtils.isNotBlank(imageCover)) {
            List<String> urls = Arrays.stream(imageCover.split(","))
                    .map(url -> webSite + url)
                    .collect(Collectors.toList());
            imageList.addAll(urls);

        }
        //去重
        imageList = imageList.stream().distinct().collect(Collectors.toList());

        HashMap result = new HashMap();
        result.put("content", content);
        result.put("images", imageList);

        return result;
    }

    private void publishArticle(WmNews wmNews) {
        Long articleId = saveArticle(wmNews);
        wmNews.setArticleId(articleId);
        updateWmNews(wmNews, PUBLISHED.getCode(), "发布成功");
    }

    private Long saveArticle(WmNews wmNews) {
        //封装articleDto
        ArticleDto articleDto = new ArticleDto();
        //拷贝属性
        BeanUtils.copyProperties(wmNews, articleDto);
        articleDto.setId(wmNews.getArticleId());
        articleDto.setFlag((byte) 0);//普通文章
        articleDto.setLayout(wmNews.getType());//文章布局
        articleDto.setWmUserId(wmNews.getUserId());//用于获取作者信息
        AdChannel adChannel = adChannelMapper.selectById(wmNews.getChannelId());
        articleDto.setChannelName(adChannel.getName());
       ResponseResult<Long> saveResult= articleFeign.saveArticle(articleDto);
       if(saveResult.getCode().intValue()!=0){
           log.error("远程调用保存文章方法失败    原因：{}    参数：{}",saveResult.getErrorMessage(),articleDto);
           CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);

       }
        return saveResult.getData();
    }
}
